package com.mankind.ssm.realm;

import com.mankind.ssm.pojo.User;
import com.mankind.ssm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * Created by Mankind on 2017/7/20.
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username =(String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        Set<String> roleName=userService.getRoles(username);
        for (String name:roleName) {
            System.out.println(username+"拥有角色:"+name);
        }
        Set<String> permissionName=userService.getPermissions(username);
        for (String name:permissionName) {
            System.out.println(username+"拥有权限:"+name);
        }
        authorizationInfo.setRoles(userService.getRoles(username));
        authorizationInfo.setStringPermissions(userService.getPermissions(username));
        return authorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username =(String) token.getPrincipal();
        System.out.println(username);
        User user = userService.selectUserByAccount(username);
        if(user == null){
                //throw new UnknownAccountException("û���ҵ����˺�");
            System.out.println("找不到用户");
            return null;
        }
        System.out.println("成功找到用户,开始登陆!");
            SimpleAuthenticationInfo autoenticationInfo = new SimpleAuthenticationInfo(user.getUserAccount(),user.getUserPassword(),getName());
        return autoenticationInfo;
    }
    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return getClass().getName();
    }
}
